<script>
    /* eslint-disable no-unused-vars */

    import axios from 'axios'
  // import md5 from 'js-md5'
  import VueCookie from 'vue-cookie'

  const _get = axios.create({
    baseURL: '/',
    method: 'GET',
    withCredentials: true,
  });

  const _post = axios.create({
    baseURL: '/',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    method: 'POST',
    withCredentials: true,
    transformRequest: [function (data) {
      var ret = '';
      for (var it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
      }
      return ret
    }]
  });

  const _multipart = axios.create({
    baseURL: '/',
    method: 'POST',
    withCredentials: true,
    transformRequest: [function (data) {
      const formData = new FormData();
      for (var it in data) {
        const realData =  data[it];
        if(realData != null) {
          formData.append(it + '', realData);
        }
      }
      return formData
    }]
  });

  export default {
    _requestTag: {},

    // 执行指定 Tag 请求
    request({tag, wrapper, isAbort}) {
      if(!wrapper) {
        return null;
      }
      if(tag != null && this._requestTag[tag]) {
          if(isAbort === false) {
              return null;
          }
          this._requestTag[tag].interrupt();
      }
      this._requestTag[tag] = wrapper;
      return wrapper;
    },

    // 中断指定 Tag 请求
    cancel({tag, msg}) {
      if(tag != null && this._requestTag[tag]) {
        if(msg) {
          this._requestTag[tag].cancel(msg);
        }
        else {
          this._requestTag[tag].interrupt();
        }
      }
    },

    // 检查是否为中断请求
    checkInterrupt (err) {
      if(err && err.message) {
        return err.message === 'interrupted';
      }
      return false;
    },

      // 获取 CPU 信息
      // mode:
      // 0 - 表示当前
      // 1 - 表示按分钟统计
      // 2 - 表示按小时统计
      // 3 - 表示按天统计
      getCpuInfo ({mode}) {
          const wrapper = requestWrapper();
          wrapper.obj.promise = _get.get('/getCpuInfo?mode=' + mode , {
              cancelToken: wrapper.getCancelToken(),
          });
          return wrapper;
      },

      // 获取内存信息
      // mode:
      // 0 - 表示当前
      // 1 - 表示按分钟统计
      // 2 - 表示按小时统计
      // 3 - 表示按天统计
      getMemoryInfo ({mode}) {
          const wrapper = requestWrapper();
          wrapper.obj.promise = _get.get('/getMemoryInfo?mode=' + mode , {
              cancelToken: wrapper.getCancelToken(),
          });
          return wrapper;
      },

      // 清理系统内存
      sweepMemoryCache () {
          const wrapper = requestWrapper();
          wrapper.obj.promise = _get.get('/sweepMemoryCache', {
              cancelToken: wrapper.getCancelToken(),
          });
          return wrapper;
      },

      // 获取设备状态
      getDeviceStatus() {
          const wrapper = requestWrapper();
          wrapper.obj.promise = _get.get('/getDeviceStatus', {
              cancelToken: wrapper.getCancelToken(),
          });
          return wrapper;
      },
      // 恢复出厂设置
      factoryReset() {
          const wrapper = requestWrapper();
          wrapper.obj.promise = _get.get('/factoryReset', {
              cancelToken: wrapper.getCancelToken(),
          });
          return wrapper;
      }

  }

  // 请求包装器
  function requestWrapper() {
    return {
      // 包装器对象
      obj: {
        // 标记是否 Canceled
        isCanceled: false,
        // Canceled 消息
        cancelMsg: 'interrupted',
      },
      analyze: function(callback) {
        return this.obj.promise.then(res => {
          this.obj.isCanceled = true;
          if(res.status === 200) {
            const data = res.data;
            if(data.status === 0) {
              callback(data.status, data.result);
            }
            else {
              callback(data.status, data.msg ? data.msg : null);
            }
          }
          else {
            callback(-1, null);
          }
        }).catch(err => {
          this.obj.isCanceled = true;
          if(this.checkInterrupt(err)) {
            return;
          }
          callback(-1, err.message ? err.message : null);
        });
      },
      // Promise then
      then: function(callback) {
        return this.obj.promise.then(data => {
          this.obj.isCanceled = true;
          callback(data);
        });
      },
      // Promise catch error
      catch: function(callback) {
        return this.obj.promise.catch(error => {
          this.obj.isCanceled = true;
          callback(error);
        });
      },
      result: function({success, failure}) {
          const wrapper = this;
          this.then(res=> {
              if(res == null) {
                  failure('请求发生异常，请重试');
                  return;
              }
              if(res.status !== 200) {
                  failure('请求失败，请重试');
                  return;
              }

              const data = res.data;
              if(data.status === 0) {
                  success(data.result);
                  return
              }
              else {
                  failure(data.msg != null ? data.msg : "请求失败，请重试");
              }
          });
          this.catch(error => {
              if(wrapper.checkInterrupt(error)) {
                  return;
              }
              failure("请求连接异常，请重试");
          })
      },
      // 取消请求
      cancel: function(msg) {
        if(this.obj.isCanceled) {
          return;
        }
        this.obj.isCanceled = true;
        if(this.obj.cancel) {
          this.obj.cancel(msg ? msg : 'canceled');
        }
        else {
          this.obj.cancelMsg = msg;
        }
      },
      // 中断请求
      interrupt: function() {
        this.cancel('interrupted');
      },
      // 获得中断 Token
      getCancelToken: function() {
        if(this.obj.cancelToken == null) {
          this.obj.cancelToken = new axios.CancelToken(cancel => {
            this.obj.cancel = cancel;
            if(this.obj.isCanceled) {
              cancel(this.obj.cancelMsg ? this.obj.cancelMsg : 'canceled');
            }
          });
        }

        return this.obj.cancelToken;
      },
      // 检查是否为中断请求
      checkInterrupt (err) {
        if(err && err.message) {
          return err.message === 'interrupted';
        }
        return false;
      },
    };
  }
</script>
